/* $RCSFile: XslHelper.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/Helpers/XslHelper.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:28  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Web;
using System.Globalization;
using System.Xml;
using System.Text.RegularExpressions;
using System.Xml.XPath;
using AddonNice.Core;
using AddonNice.Configuration;
using AddonNice.Settings;
using AddonNice.Security;

// CS 10/3/4 modified to incorporate error tracking
namespace AddonNice.Helpers
{
	/// <summary>
	/// XslHelper object, designed to be imported into an XSLT transform
	/// via XsltArgumentList.AddExtensionObject(...). Provides transform with 
	/// access to various AddonNice functions, such as BuildUrl(), IsInRoles(), data 
	/// formatting, etc. 
	/// </summary>
	public class XslHelper
	{
		PortalSettings portalSettings;
		AddonNice.Security.AddonNiceIdentity user;
		

		public XslHelper()
		{
			if (HttpContext.Current != null  )
			{
				portalSettings = (PortalSettings) HttpContext.Current.Items[StStr.strPortalSettings];
				user = AddonNiceIdentity.CurrentIdentity;
			}
		}

		public virtual string Localize(string textKey, string translation)
		{
			return LocalizeHelper.Localize(textKey, translation);
		}

		# region Data Formatting

		public string FormatTemp(string tempString, string dataScale, string outputScale)
		{
			try
			{
				double conv;

				if ( dataScale == outputScale )
				{
					conv = double.Parse(tempString,new CultureInfo(string.Empty));
					return conv.ToString("F0") + Convert.ToChar(176) + outputScale;
				}
				else if ( outputScale.ToUpper() == "C" )
				{
					conv = F2C( double.Parse(tempString, new CultureInfo(string.Empty)) );
					return conv.ToString("F0") + Convert.ToChar(176) + "C";

				}
				else
				{
					conv = C2F( double.Parse(tempString, new CultureInfo(string.Empty)) );
					return conv.ToString("F0") + Convert.ToChar(176) + "F";
				}
			}
			catch
			{
				return tempString;
			}
		}

		public double C2F(double c) 
		{
			return (1.8 * c) + 32;
		}

		public double F2C(double f) 
		{
			return (f - 32) / 1.8;
		}


		public string FormatDateTime(string dateString, string dataCulture, string formatString)
		{
			try
			{
				return FormatDateTime(dateString, dataCulture, portalSettings.PortalDataFormattingCulture.Name, formatString);
			}
			catch
			{
				return dateString;
			}
		}

		public string FormatDateTime(string dateString, string formatString)
		{
			try
			{
				return FormatDateTime(dateString, portalSettings.PortalDataFormattingCulture.Name, portalSettings.PortalDataFormattingCulture.Name, formatString);
			}
			catch
			{
				return dateString;
			}
		}

		public string FormatDateTime(string dateString)
		{
			try
			{
				return DateTime.Parse(dateString,CultureInfo.InvariantCulture).ToLongDateString();
			}
			catch
			{
				return dateString;
			}
		}

		public string FormatDateTime(string dateString, string dataCulture, string outputCulture, string formatString)
		{
			try
			{
				DateTime conv;

				if ( dataCulture.ToLower() == portalSettings.PortalDataFormattingCulture.Name.ToLower() )
				{
					conv = DateTime.ParseExact(dateString,"mm/dd/yyyy hh:mm:ss" ,new CultureInfo(dataCulture, false),DateTimeStyles.AdjustToUniversal);
				}
				else
				{
					conv = DateTime.Parse(dateString, new CultureInfo(dataCulture, false),DateTimeStyles.None);
				}
				
				if ( outputCulture.ToLower() == portalSettings.PortalDataFormattingCulture.Name.ToLower() )
					return conv.ToString(formatString);
				else
					return conv.ToString(formatString, new CultureInfo(outputCulture, false));

			}
			catch
			{
				return dateString;
			}
		}

		public string FormatNumber(string numberString, string dataCulture, string formatString)
		{
			try
			{
				return FormatNumber(numberString, dataCulture, portalSettings.PortalDataFormattingCulture.Name, formatString);
			}
			catch
			{
				return numberString;
			}
		}

		public string FormatNumber(string numberString, string dataCulture, string outputCulture, string formatString)
		{
			try
			{
				Double conv;

				if ( dataCulture.ToLower() == portalSettings.PortalDataFormattingCulture.Name.ToLower() )
				{
					conv = Double.Parse(numberString);
				}
				else
				{
					conv = Double.Parse(numberString, new CultureInfo(dataCulture, false));
				}
				
				if ( outputCulture.ToLower() == portalSettings.PortalDataFormattingCulture.Name.ToLower() )
					return conv.ToString(formatString);
				else
					return conv.ToString(formatString, new CultureInfo(outputCulture, false));

			}
			catch
			{
				return numberString;
			}
		}
		# endregion

		# region Security
		public bool CheckRoles(string authRoles)
		{
			return PortalSecurity.IsUserInRoles(authRoles);
		}
		# endregion

		# region Url Builder
		public string AddToUrl(string url, string paramKey, string paramValue)
		{
			if (url.IndexOf(paramKey) == -1)
			{
				if (url.IndexOf("?") > 0)
				{
					url = url.Trim() + "&" + paramKey.Trim() + "=" + paramValue.Trim();
				}
				else
				{
					url = url.Trim();
					url = url.Substring(0,url.LastIndexOf("/")) + "/" + paramKey.Trim() + "_" + paramValue.Trim() + url.Substring(url.LastIndexOf("/"));
				}
			}
			return url;
		}


		public string BuildUrl(string targetPage, int tabID,bool keepTargetPage,DynPageLoc loc)
		{
			targetPage  =   Regex.Replace(targetPage,@"[\.\$\^\{\[\(\|\)\*\+\?!'""]",string.Empty);
			targetPage  =   targetPage.Replace(" ","_").ToLower();
            // CS 13/2/7 to avoid links to _.aspx
            if (targetPage == "_")
                return string.Empty;
			return HttpUrlBuilder.BuildUrl("~/" + targetPage + ".aspx",keepTargetPage,loc, tabID);
		}

		public string BuildUrl(int tabID, string pathTrace,DynPageLoc loc)
		{
			char[] _delim           =   new char[]{'/'};
			pathTrace               =   pathTrace.TrimEnd(_delim);
			pathTrace               =   pathTrace.TrimStart(_delim);
			pathTrace               =   Regex.Replace(pathTrace,@"[\.\$\^\{\[\(\|\)\*\+\?!'""]",string.Empty);
			pathTrace               =   pathTrace.Replace(" ","_").ToLower();

			string targetPage       =   null;
			string customAttributes =   null;

			if (pathTrace.IndexOf("/") > 0)
			{
				targetPage          =   pathTrace.Substring(pathTrace.LastIndexOf("/") + 1);
				customAttributes    =   pathTrace.Substring(0,pathTrace.Length - targetPage.Length - 1);
			}
			else
			{
				targetPage          =   pathTrace;
			}

            // CS 13/2/7 to avoid links to _.aspx
            if (targetPage == "_")
                return string.Empty;
            return HttpUrlBuilder.BuildUrlWithCustomAttributes("~/" + targetPage + ".aspx",loc,tabID, customAttributes);
		}
		#endregion

		# region Member Access - portalSettings
		public string PortalAlias()
		{
            return portalSettings.PortalAlias;
		}

		public string BaseAlias()
		{
            return portalSettings.BaseAlias;
		}

		public string PortalID()
		{
			return portalSettings.PortalID.ToString();
		}

		public string PageID()
		{
			return portalSettings.ActivePageSettings.PageID.ToString();
		}

		public string PageName()
		{
			return portalSettings.ActivePageSettings.PageName;
		}

		public string PageTitle()
		{
			return portalSettings.ActivePageSettings.PageTitle;
		}

		public string PageKeyPhrase()
		{
			return portalSettings.ActivePageSettings.PageKeyPhrase;
		}

		public string PortalContentLanguage()
		{
			return portalSettings.PortalContentLanguage.Name;
		}

		public string PortalUILanguage()
		{
			return portalSettings.PortalUILanguage.Name;
		}

		public string PortalDataFormattingCulture()
		{
			return portalSettings.PortalDataFormattingCulture.Name;
		}

		public string PortalLayoutPath()
		{
			return portalSettings.PortalLayoutPath;
		}

		public string PortalFullPath()
		{
			return portalSettings.PortalFullPath;
		}

		public string PortalName()
		{
			return portalSettings.PortalName;
		}

		public string PortalTitle()
		{
			return portalSettings.PortalTitle;
		}

        public string UserName()
        {
            return user.Name;
        }

        public Guid CRMGuid()
        {
            return user.CrmId;
        }

        #endregion
	
		#region Member Access - moduleSettings

		#endregion

	}
}
